package org.gongliang.jfinal.common.interceptor;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.gongliang.jfinal.common.KConstant;
import org.gongliang.jfinal.common.annotation.Logs;
import org.gongliang.jfinal.common.base.Result;
import org.gongliang.jfinal.common.exception.ExceptionEnum;
import org.gongliang.jfinal.model.Log;
import org.gongliang.jfinal.model.User;
import org.gongliang.jfinal.utils.UserAgentKit;
import org.gongliang.jfinal.utils.WebKit;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.render.JsonRender;

import eu.bitwalker.useragentutils.UserAgent;

/**
 * @description 全局异常处理及日志拦截
 * @author 龚亮
 * @date 2015-05-26 09:49:19
 */
public class LogInterceptor implements Interceptor{
	

	/**
	 * 日志记录及异常拦截
	 */
	@Override
	@SuppressWarnings("all")
	public void intercept(Invocation invocation){
		Controller c=invocation.getController();
		Method method=invocation.getMethod();
		User user = c.getSessionAttr(KConstant.USER_SESSION);
		long timeConsuming=0L;
		UserAgent userAgent = UserAgent.parseUserAgentString(c.getRequest().getHeader("User-Agent")); 
		Result r = Result.success();
		Log log=new Log();
		log.setReqOk(true);
		try {
			long beginTime = System.currentTimeMillis();
			invocation.invoke();
			long endTime = System.currentTimeMillis();
			timeConsuming=endTime-beginTime;
		} catch (Exception e) {
			e.printStackTrace();
			r.setResCode(ExceptionEnum.SYS_ERROR.getResCode());
			r.setResMsg(ExceptionEnum.SYS_ERROR.getResMsg());
			log.setException(ExceptionUtils.getStackTrace(e));
			log.setReqOk(false);
			/**
			 * json异常处理
			 */
			if(c.getRender() instanceof com.jfinal.render.JsonRender){
				c.render(new JsonRender(r).forIE());
			}
		}finally{
			/**
			 * 日志记录
			 */
			if(method.isAnnotationPresent(Logs.class)&&user!=null){
				HttpServletRequest request= c.getRequest();
				Logs logs = method.getAnnotation(Logs.class);
				log.setCreateDate(new Date());
				log.setIp(WebKit.getIpAddr(request));
				log.setRemark(logs.des());
				log.setReqMethod(request.getMethod());
				if(user!=null){
					log.setCreator(user.getId());
				}
				HashMap map=new HashMap(request.getParameterMap()); 
				if(map.containsKey("password")){
					map.put("password", new String[]{"******"});
				}
				if(map.containsKey("newPassword")){
					map.put("newPassword", new String[]{"******"});
				}
				log.setReqParam(JsonKit.toJson(map));
			    log.setReqUrl(request.getRequestURI());
			    log.setUserAgent(UserAgentKit.getUserAgent(request).toString());
				log.save();
			}
		}
	}
}
